package com.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.entity.Category;
import com.service.CategoryService;

@Controller @RequestMapping("/category")
public class CategoryController {
	
	@Resource
	CategoryService categoryService;
	
	@RequestMapping("")
	public String gotoCategory(ModelMap m) {
		
		List<Category> listAndcountCategory= categoryService.listAndcountCategory();
		m.put("listAndcountCategory", listAndcountCategory);
		
		return "Category/category-list";
	}
	
	@RequestMapping("/add")
	public String addCategory(HttpServletRequest request) {
		Category category = new Category();
		category.setCategoryName(request.getParameter("categoryName"));
		category.setCategoryPid(Integer.parseInt(request.getParameter("categoryPid")));
		categoryService.addCategory(category);
		
		return "redirect:../category";
	}
	
	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable("id") Integer id) {
		categoryService.deleteCategory(id);
		
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String goupdatePage(@PathVariable("id") Integer id,ModelMap m){
		Category category = categoryService.getCategoryById(id);
		List<Category> categoryList = categoryService.listCategory();
		List<Category> listAndcountCategory= categoryService.listAndcountCategory();
		
		m.put("category", category);
		m.put("categoryList", categoryList);
		m.put("listAndcountCategory", listAndcountCategory);
		return "Category/category-update";
	}
	
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String updateCategory(HttpServletRequest request) {
		Category category = new Category();
		category.setCategoryId(Integer.parseInt(request.getParameter("categoryId")));
		category.setCategoryName(request.getParameter("categoryName"));
		category.setCategoryPid(Integer.parseInt(request.getParameter("categoryPid")));
		
		categoryService.deleteCategory(Integer.parseInt(request.getParameter("categoryId")));
		categoryService.addCategory(category);
		
		return "redirect:../category";
	}
	
}
